<script lang="ts">
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import { X } from "lucide-svelte";
  import { readDir } from "@tauri-apps/plugin-fs";
  import { resolve, homeDir } from "@tauri-apps/api/path";
  import { request } from "$lib/utils/request";
  import { auth, pre_auth, sign } from "$lib/api/admin_auth";
  import { userStore } from "$lib/stores/user.svelte";
  import { goto } from "$app/navigation";
  import { ADMIN_PATH } from "$lib/utils/consts";
  import { getContext } from "svelte";
  import type { Store as ToastStore } from "@zag-js/toast";

  const toast: ToastStore = getContext("toast");

  let sshKeyNameList = $state([] as string[]);

  let curSshName = $state("");

  let username = $state("");

  async function loadSshKeyNameList() {
    const homeDirPath = await homeDir();
    const sshDirPath = await resolve(homeDirPath, ".ssh");
    const entries = await readDir(sshDirPath);
    const nameSet = new Set<string>();
    for (const entry of entries) {
      if (entry.isDirectory) {
        continue;
      }
      nameSet.add(entry.name);
    }
    const tmpList: string[] = [];
    nameSet.forEach((name) => {
      if (!name.endsWith(".pub")) {
        if (nameSet.has(`${name}.pub`)) {
          tmpList.push(name);
        }
      }
    });
    sshKeyNameList = tmpList;
    if (tmpList.length > 0) {
      curSshName = tmpList[0];
    }
  }

  async function doLogin() {
    if (username == "" || curSshName == "") {
      return;
    }
    const preRes = await request(
      pre_auth({
        user_name: username,
      })
    );
    const home = await homeDir();
    const privKey = await resolve(home, ".ssh", curSshName);
    const signRes = await sign(privKey, preRes.to_sign_str);
    await request(
      auth({
        admin_session_id: preRes.admin_session_id,
        sign: signRes,
      })
    );
    userStore.adminUserSession = preRes.admin_session_id;
    userStore.adminUserName = username;
    toast.create({
      title: "成功",
      description: "登录成功!",
      type: "success",
    });
    goto(ADMIN_PATH);
    userStore.showAdminLoginModal = false;
  }

  loadSshKeyNameList();
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      userStore.showAdminLoginModal = false;
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">登录管理后台</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => (userStore.showAdminLoginModal = false)}
      >
        <X />
      </button>
    </header>

    <label class="label">
      <span class="label-text">用户名</span>
      <input
        class="input bg-surface-50-950 rounded-none"
        type="text"
        bind:value={username}
        placeholder="请输入用户名"
      />
    </label>

    <label class="label">
      <span class="label-text">密钥</span>
      <select
        class="select bg-surface-50-950 rounded-none"
        bind:value={curSshName}
      >
        {#each sshKeyNameList as sshKeyName}
          <option value={sshKeyName}>{sshKeyName}</option>
        {/each}
      </select>
    </label>

    <footer class="flex justify-end gap-4">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => (userStore.showAdminLoginModal = false)}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-primary-900-100"
        disabled={username == "" || curSshName == ""}
        onclick={() => doLogin()}>登录</button
      >
    </footer>
  {/snippet}
</Modal>
